package com.travel.authserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.client.utils.JSONUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.travel.authserver.feign.MemberFeignService;
import com.travel.authserver.feign.ThirdPartFeignService;
import com.travel.authserver.vo.UserLoginVo;
import com.travel.authserver.vo.UserRegistVo;
import com.travel.common.constant.AuthServerConstant;
import com.travel.common.exception.BizCodeEnum;
import com.travel.common.utils.R;
import com.travel.common.vo.MemberRespVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.travel.common.constant.AuthServerConstant.LOGIN_USER;

@Slf4j
@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/login.html")
    public String login(){
        return "login";
    }

    @GetMapping("/regist.html")
    public String regist(){
        return "regist";
    }


    /**
     * 获取短信验证码
     * @param phone
     * @return
     */
    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone")String phone){

        //TODO 1. 接口防刷

        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if(System.currentTimeMillis() - l < 60000){
                //60秒内不能再发验证码
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(),BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
            }
        }
        //2. 验证码的再次校验。redis：存key-phone value-code sms:code:13711812869 -> 123456
        Random random = new Random();
        String code = String.valueOf(random.nextInt(900000) + 100000); //生成随机6位数
        //验证码后缀：加上 _当前系统时间
        String redisStorage = code+"_"+System.currentTimeMillis();
        //redis缓存验证码，防止同一个phone在60秒内再次发送验证码 10分钟有效
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone,redisStorage,10, TimeUnit.MINUTES);

        System.out.println("phone=="+phone);
        System.out.println("code=="+code);

        R r = thirdPartFeignService.sendCode(phone, code);
        if(r.getCode() == 0){
            System.out.println("yes");
            return R.ok();
        }else{
            System.out.println("获取验证码异常");
            return R.error();
        }
    }

    /**
     * 重定向携带数据，利用session原理，将数据放到session中
     * 只要跳转到下一个页面取出这个数据后，session里面的数据就会删掉
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result,
                         RedirectAttributes redirectAttributes,
                         HttpSession session){
        //数据校验出错
        if(result.hasErrors()){
            //取出错误信息，放在map中
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(fieldError -> {
                return fieldError.getField();
            }, fieldError -> {
                return fieldError.getDefaultMessage();
            }));

            redirectAttributes.addFlashAttribute("errors",errors);

            //return "forward:/reg.html"
            //异常：Request method 'Post' not supported
            //用户注册 -> /regist [Post] -> 转发/regist.html（路径映射默认都是get方式访问的）

            //校验出错，转发至注册页
            return "redirect:http://auth.travel.com/regist.html";
        }

        //1. 校验验证码
        String code = vo.getCode();

        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if(!StringUtils.isEmpty(s)){
            if(code.equals(s.split("_")[0])){
                //删除验证码：令牌机制
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //验证码通过 真正注册，调用远程服务进行注册
                R r = memberFeignService.regist(vo);
                if(r.getCode() == 0){
                    //成功
                    return "redirect:http://auth.travel.com/login.html";
                }else{
                    HashMap<String, String> errors = new HashMap<>();
                    errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.travel.com/regist.html";
                }

            }else{
                //验证码错误
                HashMap<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                //校验出错，转发至注册页
                return "redirect:http://auth.travel.com/regist.html";
            }
        }else{
            HashMap<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            //校验出错，转发至注册页
            return "redirect:http://auth.travel.com/regist.html";
        }

    }

    @PostMapping("/login")
    public String login(UserLoginVo vo,
                        RedirectAttributes redirectAttributes,
                        HttpSession session) throws JsonProcessingException {
        //远程登录
        R login = memberFeignService.login(vo);
        if(login.getCode() == 0){
            MemberRespVo data = login.getData("data", new TypeReference<MemberRespVo>() {
            });
            //成功 放到session中
            session.setAttribute(LOGIN_USER,data);

            //保存用户信息到redis中，ttl：30min
            String s = JSON.toJSONString(data);
            stringRedisTemplate.opsForValue().set(LOGIN_USER,s,30,TimeUnit.MINUTES);

            log.info(data.toString());
            log.info(s);
            return "redirect:http://travel.com";
        }else{
            HashMap<String, String> errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.travel.com/login.html";
        }

    }

}
